package org.example.sercurity;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.Data;
import org.example.entity.Menu;
import org.example.entity.Role;
import org.example.entity.User;
import org.example.sercurity.UserDeatilImpl;
import org.example.service.IMenuService;
import org.example.service.IRoleService;
import org.example.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;


import javax.security.auth.login.LoginException;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class PermssionImpl implements UserDetailsService {
    @Autowired
    private IRoleService roleService;
    @Autowired
    private IMenuService menuService;
    @Autowired
    private IUserService userService;

    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        User user=userService.getOne(Wrappers.lambdaQuery(User.class).eq(User::getUserName,userName));
        if(user == null){
            throw new UsernameNotFoundException("用户不存在");
        }
        UserDeatilImpl userDetails = new UserDeatilImpl();
        userDetails.setUsername(user.getUserName());
        userDetails.setPassword(user.getPassword());
        userDetails.setNickName(user.getNickName());
        Perms perms = this.getPerms(user);
        userDetails.setRoleNames(perms.roleKeys);
        userDetails.setPermsList(perms.permsLsit);
        return userDetails;
    }

    @Data
    public static class Perms {
        private Set<String> roleKeys;
        private Set<String> permsLsit;
    }

    public Perms getPerms(User user){
        List<Role> roleList = roleService.getByUsername(user.getUserName());
        List<Menu> menuList = menuService.getByRoleIdList(roleList.stream().mapToLong(Role::getRoleId).boxed().collect(Collectors.toList()));
        Perms perms =new Perms();
        perms.setRoleKeys(roleList.stream().map(Role::getRoleKey).collect(Collectors.toSet()));
        perms.setPermsLsit(menuList.stream().filter(item -> StringUtils.hasText(item.getPerms()))
                .map(Menu::getPerms).collect(Collectors.toSet()));
        return perms;
    }


}
